package com.itcast.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * create by IntelliJ IDEA
 * Creator: HuangRZ
 * Email: huangrz11@163.com
 * Date: 2018/2/24
 * Description:
 **/
@RestController
//@EnableAutoConfiguration
public class DemoController {

    @Value("${cupSize}")
    private String cupSize;

    //获取properties的属性值，并自动转换类型。
    @Value("${age}")
    private Integer age;

    @GetMapping("/hello")
    public String hello(){
        return "Hello World! Hello spring boot!";
    }

    @GetMapping("/get")
    public String get(){
        return "cupSize: "+cupSize+", age: "+age;
    }

    @Value("${content}")
    private String content;

    @GetMapping("/content")
    public String content(){
        return content;
    }

    @Autowired
    private GirlProperties girlProperties;

    @GetMapping({"/girl", "/girls"})
    public String girl(){
        return "Girl: cupSize: "+girlProperties.getCupSize()+", age: "+girlProperties.getAge();
    }

    @Autowired
    private GirlRepository girlRepository;

    @PostMapping("/save")
    private Object save(
            @RequestParam("cupSize") String cupSize,
            @RequestParam("age") Integer age
    ){
        return girlRepository.save(new Girl(cupSize, age));
    }

    @PostMapping("/add")
    public Object add(@Valid Girl girl, BindingResult result){
        if (result.hasErrors()){
            System.out.println(result.getFieldError().getDefaultMessage());
            return result.getFieldError().getDefaultMessage();
        }
        return girlRepository.save(girl);
    }
}
